package com.zhiyou.app.shop.website.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Component;

import com.zhiyou.app.shop.manager.dao.impl.BaseHibernateDAO;
import com.zhiyou.app.shop.website.dao.ITransferInfoDao;
import com.zhiyou.app.shop.website.dao.pojo.TransferInfo;

@Component
public class TransferInfoDaoImpl extends BaseHibernateDAO<TransferInfo, String> implements ITransferInfoDao {

	public TransferInfoDaoImpl(){
		super(TransferInfo.class);
	}

	public List findTransfer(final String userAccount,final int startNum, final int pagesize) {
		final String sql = "select user_id,to_user_id,amount,post_time from " +
				"(select t1.user_id,t1.to_user_id,t1.amount,t1.post_time from transfer_info t1 where t1.user_id=? " +
				"UNION select t2.user_id,t2.to_user_id,t2.amount,t2.post_time from transfer_info t2 where t2.to_user_id= ?) a " +
				"order by a.post_time desc limit ?,?";
		List list = hibernateTemplate.execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				SQLQuery query = session.createSQLQuery(sql);
				query.setString(0, userAccount);
				query.setString(1, userAccount);
				query.setInteger(2, startNum);
				query.setInteger(3, pagesize);
				query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
				return query.list();
			}
		});
		
		
		return list;
	}

	public int findTransferCnt(final String userAccount) {
		final String sql = "select count(1) cnt from " +
				"(select t1.user_id,t1.to_user_id,t1.amount,t1.post_time from transfer_info t1 where t1.user_id=? " +
				"UNION select t2.user_id,t2.to_user_id,t2.amount,t2.post_time from transfer_info t2 where t2.to_user_id= ?) a";
		Integer cnt = hibernateTemplate.execute(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session)
					throws HibernateException {
				SQLQuery query = session.createSQLQuery(sql);
				query.setString(0, userAccount);
				query.setString(1, userAccount);
				return (Integer)query.addScalar("cnt", new org.hibernate.type.IntegerType()).uniqueResult();
			}
		});
		return cnt;
	}
	
	
}
